//
// Created by Lenovo on 24-7-13.
//

#ifndef UNTITLED15_SERIAL_H
#define UNTITLED15_SERIAL_H

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<termios.h>

int serial_fd;

int init_serial_port() {
    serial_fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (serial_fd == -1) {
        perror("Failed to open serial port");
        return -1;
    }
    fcntl(serial_fd, F_SETFL, 0);
    isatty(STDIN_FILENO);
    //struct
    struct termios options;
    //获取串口当前参数
    tcgetattr(serial_fd, &options);
    //波特率
    cfsetospeed(&options, B115200);
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CSTOPB;
    options.c_iflag &= ~PARENB;
    options.c_cflag &= ~CRTSCTS;
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;
    tcflush(serial_fd, TCIFLUSH);
    // 应用新的设置
    if (tcsetattr(serial_fd, TCSANOW, &options) != 0) {
        perror("Error from tcsetattr");
        close(serial_fd);
        return -1;
    }
}

// 串口写入数据函数
int serial_write(const void *data, size_t size) {
    if (serial_fd == -1) {
        fprintf(stderr, "Serial port not initialized.\n");
        return -1;
    }
    ssize_t ret = write(serial_fd, data, size);
    if (ret == -1) {
        perror("Error writing to serial port");
        return -1;
    }
    return ret; // 返回写入的字节数
}

// 串口读取数据函数
int serial_read(void *buffer, size_t size) {
    if (serial_fd == -1) {
        fprintf(stderr, "Serial port not initialized.\n");
        return -1;
    }

    ssize_t ret = read(serial_fd, buffer, size);
    if (ret == -1) {
        perror("Error reading from serial port");
        return -1;
    }
    return ret; // 返回读取的字节数
}

#endif //UNTITLED15_SERIAL_H
